﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Streambolics.Web
{
    /// <summary>
    ///     An object that maintains a local copy of a web page, and updates it
    ///     regularly.
    /// </summary>

    public class WebPageContents
    {
        private DateTime _NextFetch = DateTime.Now;
        private DateTime _Timeout;

        private TimeSpan _FetchDelay = 30.Seconds ();
        private TimeSpan _TimeoutDelay = 1.Minutes ();

        private HttpQueryJob _Query;
        private string _LastValue;

        private string _Url;
        private JobQueue<HttpQueryJob> _Queue;

        public WebPageContents (string aUrl)
        {
            _Url = aUrl;
        }

        public void Attach (JobQueue<HttpQueryJob> aQueue)
        {
            _Queue = aQueue;
        }

        /// <summary>
        ///     Returns the latest contents of the fetched page.
        /// </summary>
        /// <returns>
        ///     Either a string containing the HTML of the page, or null
        ///     if the page is not yet retrieved.
        /// </returns>

        public string TimedGetActualContent ()
        {
            if (_Query != null)
            {
                if (_Query.Complete)
                {
                    _LastValue = "Hello";
                    _Query = null;
                    return _LastValue;
                }
                else
                {
                    if (_Timeout.Reached ())
                    {
                        _Query = null;
                    }
                    return null;
                }
            }
            if (_NextFetch.Reached ())
            {
                _NextFetch = _FetchDelay.FromNow ();
                if (_Queue != null && _Queue.IsRunning)
                {
                    _Query = new HttpQueryJob (_Url);
                    _Queue.Push (_Query);
                }
            }
            return null;
        }
    }
}
